import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { SortOrder } from 'mongoose';
import { Model, Types } from 'mongoose';
import {Journey, JourneyDocument } from './schemas/journey.schema';
import { create } from 'domain';

interface getJoruneysByPageInterface{
  page: number;
  limit: number;
  departure: string;
  destination: string
  date: string;
  sort: string;
  keyword: string;
  price: string | number
}


@Injectable()
export class JourneyService {
  constructor(
    @InjectModel(Journey.name) private readonly journeyModel: Model<JourneyDocument>,
  ) {}

  async createJourney(journey: Journey): Promise<Journey> {
    const createdJourney = new this.journeyModel(journey);
    return createdJourney.save();
  }
  async findAll(): Promise<any[]> {
    return this.journeyModel.find().exec();
  }

  async findJoruneyById(id: string | number): Promise<any | undefined> {
    const objectId = new Types.ObjectId(id);
    const res = await this.journeyModel.findOne({_id: objectId}).exec();
    return res
  }

  async countJoruneysToday(publisher_id: string): Promise<number> {
    const startOfDay = new Date();
    startOfDay.setHours(0, 0, 0, 0);

    const endOfDay = new Date();
    endOfDay.setHours(23, 59, 59, 999);

    // Assuming 'createdAt' is the field storing the creation date
    return await this.journeyModel.countDocuments({
        publisher_id,
        created_at: { $gte: startOfDay, $lte: endOfDay }
    });
  }


  async getJoruneysByPage({ page, limit, departure, destination, date, sort, keyword, price }: getJoruneysByPageInterface) {
    const query: any = {};
    const orConditions: any[] = [];
  
    if (departure) {
      orConditions.push({ departure: { $regex: new RegExp(departure, 'i') } });
    }
    if (destination) {
      orConditions.push({ destination : {$regex: new RegExp(destination, 'i')}});
    }
    if (date) {
      orConditions.push({ date });
    }
    if (price) {
      orConditions.push({ price });
    }
  
    // 处理关键字搜索
    let textSearchCondition = {};
    if (keyword) {
      textSearchCondition = { $text: { $search: keyword } };
    }
  
    if (orConditions.length > 0) {
      query.$or = orConditions;
    }
  
    if (orConditions.length === 0 && !keyword) {
      throw new Error("At least one of 'departure', 'destination', 'date', 'price', or 'keyword' must be provided.");
    }

    // 打印查询条件以进行调试
    console.log("Query Conditions:", JSON.stringify(query), textSearchCondition);
  
    const aggregationPipeline = [
      { $match: { ...query } }, // 合并查询条件
      // { $match: { publisher_id: { $exists: true, $ne: null } } }, // 确保 publisher_id 存在
      { $addFields: { 
        publisher_id: { $toObjectId: "$publisher_id" }, // 转换为 ObjectId
        // created_at: { $dateFromString: { dateString: "$created_at" } } // 将字符串转换为日期对象
        }
      }, // 转换为 ObjectId
      {$lookup:{
        from: 'users', // 关联的集合名称
        localField: 'publisher_id', // 当前集合中的字段
        foreignField: '_id', // 关联集合中的字段
        as: 'publisher' // 关联后的结果字段名
      }},
      // { $unwind: '$publisher', preserveNullAndEmptyArrays: true }, // 解构关联后的结果
      // { $sort: { created_at: sort === 'asc' ? 1 : -1 } }, // 按创建时间降序或升序排序
            // 明确指定排序方向为字面量类型
      { $sort: { created_at: (sort === 'asc' ? 1 : -1) as 1 | -1 } },  // 按创建时间降序或升序排序
      { $facet: {
          data: [
            { $skip: (page - 1) * limit },
            { $limit: limit }
          ],
          totalCount: [
            { $count: "count" }
          ]
        }
      }
    ];
  
    const result = await this.journeyModel.aggregate(aggregationPipeline).exec();
    const journeys = result[0]?.data || [];
    const totalCount = result[0]?.totalCount[0]?.count || 0;
  
    return { data: journeys.map(item => {
      return {
        ...item,
        publisher: item.publisher[0] || null
      };
    }), total: totalCount };
  }

  
}